"""Template Handler class."""

import logging
import os
import mako.lookup
import tornado.web
import yaml
from gaweb.master import excepts
from gaweb.master import helpers


class TemplateHandler(tornado.web.RequestHandler):
    """Handler for rendering templates.

    All calls to this handler must provide a template_id=XXX in the query
    string. From there, some methods require a session_id=YYY to be provided
    as well.
    """
    def initialize(self, master):
        self.master = master
        template_dir_path = os.path.join(os.path.dirname(__file__), '..', 'templates')
        self.lookup = mako.lookup.TemplateLookup(directories=[template_dir_path])

    def get(self):
        template_id = self.get_argument('template_id')

        try:
            if template_id == 'about':
                self.render_about()
            elif template_id == 'display':
                self.render_display()
            elif template_id == 'navigator':
                self.render_navigator()
            elif template_id == 'open':
                self.render_open()
            else:
                self.write('Template id not found')
        except Exception, e:
            print e
            logging.error(e)
            self.write({'template_id': template_id,
                        'error': -1,
                        'message': 'Unknown error.'})


    def render_about(self):
        """Render the About dialog template."""
        template = self.lookup.get_template('about.tpl')
        self.write({'template': template.render()})

    def render_display(self):
        """Renders the Display Variables template."""
        session_id = self.get_argument('session_id')
        
        files = self.master.handle_varinfo(session_id)
        template = self.lookup.get_template('display.tpl')

        self.write({'template': template.render(files=files),
                    'files': files})

    def render_navigator(self):
        """Renders the Navigator template.

        Also returns the dims dictionary, if available.

        Error numbers:
          1 -> session not located in master's server dictionary
        """
        session_id = self.get_argument('session_id')
        template = self.lookup.get_template('navigator.tpl')

        try:
            diminfo = self.master.handle_diminfo(session_id)
            self.write({'template': template.render(),
                        'dims': diminfo['dims'],
                        'ctlinfo': diminfo['ctlinfo']})
        except excepts.NoFilesOpenedError:
            self.write({'template': template.render(),
                        'dims': None,
                        'ctlinfo': None})
        except excepts.SessionError:
            self.write({'error': 1})

    def render_open(self):
        """Renders the Open Dataset template."""


        template = self.lookup.get_template('open.tpl')
        
        try:
            featured = helpers.read_config('featured.yaml')
        except IOError:
            featured = None
        except yaml.parser.ParserError:
            featured = None
        except:
            featured = None
        
        self.write({'template': template.render(featured=featured),
                    'featured': featured})
    
